package com.dwxt.race.controller;

import com.dwxt.race.service.WxPayService;
import com.dwxt.race.service.ZfbPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RequestMapping("/race/payBack")
@RestController
@Slf4j
public class PayForBackController {


    @Autowired
    private ZfbPayService zfbService;

    @Autowired
    private WxPayService wxService;

    /**
     * 支付宝支付回调
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/zfb/callback")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter responseWriter = response.getWriter();
        try {
            Map<String, String> params = getZFBRespMap(request);
            String result = zfbService.checkParamsZFB(params);
            responseWriter.write(result);
        } catch (Exception e) {
            log.error(e.toString());
            responseWriter.write("fail");
        }
    }

    private Map<String, String> getZFBRespMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            log.info(name + "：" + valueStr);
            params.put(name, valueStr);
        }
        return params;
    }


    /**
     * 微信支付回调接口
     */
    @RequestMapping("/wx/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String resXml = "";
        try {
            resXml = getResXmlString(request);
            log.info("微信支付异步通知请求包: {}", resXml);
            String payBack = wxService.payBack(resXml);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(payBack);
        } catch (Exception e) {
            log.error("微信支付回调通知失败", e);
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(result);
        }
    }

    private String getResXmlString(HttpServletRequest request) throws IOException {
        InputStream is = request.getInputStream();
        //将InputStream转换成String
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        return sb.toString();
    }

}
